package io.plus.user_interface.server;

import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.interactive.user_interface.GroupListener;
import io.plus.server.Server;
import io.plus.user_interface.common.UserConfiguration;
import io.plus.user_interface.common.message.RedisMessageHelper;

import java.io.IOException;


public class ServerStarter {

    private ServerAioHandlerImpl serverAioHandlerImpl = null;
    private ServerConfigurationImpl serverConfigImpl = null;
    private GroupListener groupListener = null;
    private Server server = null;
    private UserConfiguration userConfiguration = null;


    public ServerStarter(UserConfiguration userConfiguration) {
        this.userConfiguration = userConfiguration;
        init();
    }

    public static void main(String[] args) throws Exception {
        UserConfiguration userConfiguration = new UserConfiguration("localhost", 6666);

        ServerStarter serverStarter = new ServerStarter(userConfiguration);

        serverStarter.start();
        serverStarter.stop();
    }

    public void init() {
        System.setProperty("tio.default.read.buffer.size", String.valueOf(userConfiguration.getReadBufferSize()));
        serverAioHandlerImpl = new ServerAioHandlerImpl(userConfiguration);
        GroupListener groupListener = userConfiguration.getGroupListener();
        if (groupListener == null) {
            userConfiguration.setGroupListener(new GroupListener() {
                @Override
                public void onAfterBind(AsynchronousSocketChannelContext asynchronousSocketChannelContext, String group) throws Exception {

                }

                @Override
                public void onAfterUnbind(AsynchronousSocketChannelContext asynchronousSocketChannelContext, String group) throws Exception {

                }
            });
        }
        this.groupListener = userConfiguration.getGroupListener();
        serverConfigImpl = new ServerConfigurationImpl(userConfiguration, serverAioHandlerImpl);
        serverConfigImpl.setGroupListener(this.groupListener);
        if (userConfiguration.getMessageHelper() == null) {
            userConfiguration.setMessageHelper(new RedisMessageHelper(userConfiguration));
        }

        server = new Server(serverConfigImpl);
    }

    public void start() throws IOException {
        server.start(this.userConfiguration.getBindIp(), this.userConfiguration.getBindPort());
    }

    public void stop() {
        server.stop();
    }
}
